package com.sixmac.aop;

import com.sixmac.annotation.AuthUser;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.cache.CacheKit;
import com.sixmac.core.toolbox.kit.HttpKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.module.Installer;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.junit.Test;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 说明：用户授权验证
 * Created by liGang on 2018/1/17.
 */
@Aspect
@Component
public class UserTokenAop {

    @Pointcut(value = "@annotation(com.sixmac.annotation.AuthUser)")
    private void cutBefore() {
        System.out.println("===================UserTokenAop===================");
    }

    @Around("cutBefore()")
    public Object doValidator(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = HttpKit.getRequest();
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        AuthUser authUser = method.getAnnotation(AuthUser.class);
        Object[] args = point.getArgs();
        String token = request.getParameter("token");
        Installer user = null;
        if (StringUtils.isNotBlank(token) && token.contains("$")) {
            Integer id = Convert.toInt(token.replaceAll("[^\\d]", ""));
            user = Blade.create(Installer.class).findById(id);
            if (user == null) {
                return new AjaxResult().addError("用户id:" + id + "不存在");
            }
        } else {
            user = CacheKit.get(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token);
            if ((user == null) && authUser.requisite()) {
                return new AjaxResult().addError("无效的token").setCode(8);
            }
        }
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof Installer)
                args[i] = user;
        }

        return point.proceed(args);
    }

    @Test
    public void te() {
        String s = "${12}";
        if (s.contains("$")) {
            System.out.print(s.replaceAll("[^\\d]", ""));
        }
        ;
    }


}
